package kr.pe.johnkim.chattingday.mobile.rest.controller;

import kr.pe.johnkim.chattingday.mobile.domain.ChattingDayGatheringJoiner;
import kr.pe.johnkim.chattingday.mobile.domain.ChattingDayGatheringMessage;
import kr.pe.johnkim.chattingday.mobile.domain.ChattingDayMember;
import kr.pe.johnkim.chattingday.mobile.rest.service.ChattingDayGatheringJoinerService;
import kr.pe.johnkim.chattingday.mobile.rest.service.ChattingDayGatheringMessageService;
import kr.pe.johnkim.chattingday.mobile.util.ChattingDayGCM;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Chatting Day 채팅방 메시지 Controller 클래스 이다.
 * 
 * @author : johnkim <cale9797@gmail.com / Bettersoft Inc,.>
 * @Date : 12. 6. 13
 */

@Controller
@Path("/chattingDayGatheringMessageController")
public class ChattingDayGatheringMessageController {

    // SLF4J Logging
	private Logger logger = LoggerFactory.getLogger(ChattingDayGatheringMessageController.class);

    @Autowired
    private ChattingDayGatheringMessageService chattingDayGatheringMessageService = null;

    @Autowired
    private ChattingDayGatheringJoinerService chattingDayGatheringJoinerService = null;

    @Autowired
    private ChattingDayGCM chattingDayGCM = null;

    private List<ChattingDayMember> registrationIdList;

    /**
     * 채팅 메시지를 등록 한다.
     *
     * 등록에 성공하면 채팅방 참여자들에게 C2DM Push 를 날린다.
     *
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/registerGatheringMessage")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public ChattingDayGatheringMessage registerGatheringMessage(InputStream is) throws Exception {
        logger.info("registerGatheringMessage");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonGatheringMessage = new JSONObject(line);
        JSONObject jsonGatheringMessage2 = jsonGatheringMessage.getJSONObject("chattingDayGatheringMessage");

        /**
         * 채팅방 메시지를 저장하기 위한 파라메터.
         */
        ChattingDayGatheringMessage parameterGatheringMessage = new ChattingDayGatheringMessage();

        parameterGatheringMessage.setId(jsonGatheringMessage2.getString("id"));
        parameterGatheringMessage.setContent(jsonGatheringMessage2.getString("content"));
        parameterGatheringMessage.setFileUrl(jsonGatheringMessage2.getString("fileUrl"));
        parameterGatheringMessage.setLikeIt(jsonGatheringMessage2.getString("likeIt"));
        parameterGatheringMessage.setSpamYn(jsonGatheringMessage2.getString("spamYn"));
        parameterGatheringMessage.setActivateYn(jsonGatheringMessage2.getString("activateYn"));
        parameterGatheringMessage.setModifyDate(jsonGatheringMessage2.getString("modifyDate"));
        parameterGatheringMessage.setRegisterDate(jsonGatheringMessage2.getString("registerDate"));
        parameterGatheringMessage.setChattingDayGatheringsIdChattingDayGatherings(jsonGatheringMessage2.getString("chattingDayGatheringsIdChattingDayGatherings"));
        parameterGatheringMessage.setChattingDayGatheringId(jsonGatheringMessage2.getString("chattingDayGatheringId"));

        logger.info("id                                           : {}", parameterGatheringMessage.getId());
        logger.info("content                                      : {}", parameterGatheringMessage.getContent());
        logger.info("fileUrl                                      : {}", parameterGatheringMessage.getFileUrl());
        logger.info("likeIt                                       : {}", parameterGatheringMessage.getLikeIt());
        logger.info("spamYn                                       : {}", parameterGatheringMessage.getSpamYn());
        logger.info("activateYn                                   : {}", parameterGatheringMessage.getActivateYn());
        logger.info("modifyDate                                   : {}", parameterGatheringMessage.getModifyDate());
        logger.info("registerDate                                 : {}", parameterGatheringMessage.getRegisterDate());
        logger.info("chattingDayGatheringsIdChattingDayGatherings : {}", parameterGatheringMessage.getChattingDayGatheringsIdChattingDayGatherings());
        logger.info("chattingDayGatheringId                       : {}", parameterGatheringMessage.getChattingDayGatheringId());

        /**
         * C2DM Push 를 발송하기 위한 파라메터.
         */
        ChattingDayGatheringJoiner parameterGatheringJoiner = new ChattingDayGatheringJoiner();

        parameterGatheringJoiner.setChattingDayGatheringsIdChattingDayGatherings(jsonGatheringMessage2.getString("chattingDayGatheringsIdChattingDayGatherings"));
        parameterGatheringJoiner.setChattingDayGatheringId(jsonGatheringMessage2.getString("chattingDayGatheringId"));
        parameterGatheringJoiner.setActivateYn(jsonGatheringMessage2.getString("activateYn"));

        logger.info("activateYn                                   : {}", parameterGatheringMessage.getActivateYn());
        logger.info("chattingDayGatheringsIdChattingDayGatherings : {}", parameterGatheringMessage.getChattingDayGatheringsIdChattingDayGatherings());
        logger.info("chattingDayGatheringId                       : {}", parameterGatheringMessage.getChattingDayGatheringId());

        /**
         * 채팅방 메시지 저장 결과를 반환하기 위한 파라메터.
         */
        ChattingDayGatheringMessage resultGatheringMessage = new ChattingDayGatheringMessage();

        /**
         * 채팅방 참여자의 REGISTRATION ID 목록을 가져 와서 C2DM Push 를 발송 한다.
         *
         * 채팅방의 새로운 메시지인 경우 : "NEW_GATHERING_MESSAGE"
         */
        if(chattingDayGatheringMessageService.registerGatheringMessage(parameterGatheringMessage)) {

            // 채팅방 참여자들의 registration id 목록을 가져 온다.
            registrationIdList = chattingDayGatheringJoinerService.selectRegistrationIdList(parameterGatheringJoiner);

            logger.info("registrationIdList.size() : {}", registrationIdList.size());

            /**
             * 일반 로직이 좋은지 thread 가 좋은지 테스트 해서 결정할 것.
             */

            for(int i=0 ; i<registrationIdList.size() ; i++) {
//                chattingDayC2DM.androidPush(registrationIdList.get(i).getRegistrationId(), "", "NEW_GATHERING_MESSAGE");
                chattingDayGCM.sendMessage(registrationIdList.get(i).getRegistrationId(), "NEW_GATHERING_MESSAGE");
            }

//            Thread thread = new Thread(null, androidPush, "C2DM Android Push");
//            thread.start();

            resultGatheringMessage.setResult("SUCCESS");
        } else {
            resultGatheringMessage.setResult("FAIL");
        }

        return resultGatheringMessage;
    }

    /**
     * C2DM Push 를 thread 로 처리 한다?
     */
//    private Runnable androidPush = new Runnable() {
//        @Override
//        public void run() {
//            logger.info("androidPush");
//            logger.info("registrationIdList.size() : {}", registrationIdList.size());
//
//            for(int i=0 ; i<registrationIdList.size() ; i++) {
//                chattingDayC2DM.androidPush(registrationIdList.get(i).getRegistrationId(), "", "NEW_GATHERING_MESSAGE");
//            }
//        }
//    };



    @POST
    @Path("/testGCM")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public void testGCM(InputStream is) throws Exception {
        logger.info("testGCM");
        
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonMember = new JSONObject(line);
        JSONObject jsonMember2 = jsonMember.getJSONObject("chattingDayMember");

        ChattingDayMember parameterMember = new ChattingDayMember();

        parameterMember.setRegistrationId(jsonMember2.getString("registrationId"));

        logger.info("registrationId : {}", parameterMember.getRegistrationId());

//        chattingDayC2DM.sendMessage(parameterMember.getRegistrationId());

        chattingDayGCM.sendMessage(parameterMember.getRegistrationId(), "NEW_GATHERING_MESSAGE");
    }




    /**
     * 채팅방 메시지를 비활성화 한다.
     * 
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/updateDeactivateGatheringMessage")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public ChattingDayGatheringMessage updateDeactivateGatheringMessage(InputStream is) throws Exception {
        logger.info("updateDeactivateGatheringMessage");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonGatheringMessage = new JSONObject(line);
        JSONObject jsonGatheringMessage2 = jsonGatheringMessage.getJSONObject("chattingDayGatheringMessage");

        ChattingDayGatheringMessage parameterGatheringMessage = new ChattingDayGatheringMessage();

        parameterGatheringMessage.setChattingDayGatheringsIdChattingDayGatherings(jsonGatheringMessage2.getString("chattingDayGatheringsIdChattingDayGatherings"));
        parameterGatheringMessage.setChattingDayGatheringId(jsonGatheringMessage2.getString("chattingDayGatheringId"));
        parameterGatheringMessage.setId(jsonGatheringMessage2.getString("id"));
        parameterGatheringMessage.setActivateYn(jsonGatheringMessage2.getString("activateYn"));
        parameterGatheringMessage.setModifyDate(jsonGatheringMessage2.getString("modifyDate"));

        logger.info("chattingDayGatheringsIdChattingDayGatherings : {}", parameterGatheringMessage.getChattingDayGatheringsIdChattingDayGatherings());
        logger.info("chattingDayGatheringId                       : {}", parameterGatheringMessage.getChattingDayGatheringId());
        logger.info("id                                           : {}", parameterGatheringMessage.getId());
        logger.info("activateYn                                   : {}", parameterGatheringMessage.getActivateYn());
        logger.info("modifyDate                                   : {}", parameterGatheringMessage.getModifyDate());

        ChattingDayGatheringMessage resultGatheringMessage = new ChattingDayGatheringMessage();

        if(chattingDayGatheringMessageService.updateDeactivateGatheringMessage(parameterGatheringMessage)) {
            resultGatheringMessage.setResult("SUCCESS");
        } else {
            resultGatheringMessage.setResult("FAIL");
        }

        return resultGatheringMessage;
    }

    /**
     * 채팅방의 모든 메시지들을 비활성화 한다.
     * 
     * @param is
     * @return
     * @throws Exception
     */
    @POST
    @Path("/updateDeactivateAllGatheringMessage")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public ChattingDayGatheringMessage updateDeactivateAllGatheringMessage(InputStream is) throws Exception {
        logger.info("updateDeactivateAllGatheringMessage");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonGatheringMessage = new JSONObject(line);
        JSONObject jsonGatheringMessage2 = jsonGatheringMessage.getJSONObject("chattingDayGatheringMessage");

        ChattingDayGatheringMessage parameterGatheringMessage = new ChattingDayGatheringMessage();

        parameterGatheringMessage.setChattingDayGatheringsIdChattingDayGatherings(jsonGatheringMessage2.getString("chattingDayGatheringsIdChattingDayGatherings"));
        parameterGatheringMessage.setId(jsonGatheringMessage2.getString("id"));
        parameterGatheringMessage.setActivateYn(jsonGatheringMessage2.getString("activateYn"));
        parameterGatheringMessage.setModifyDate(jsonGatheringMessage2.getString("modifyDate"));

        logger.info("chattingDayGatheringsIdChattingDayGatherings : {}", parameterGatheringMessage.getChattingDayGatheringsIdChattingDayGatherings());
        logger.info("id                                           : {}", parameterGatheringMessage.getId());
        logger.info("activateYn                                   : {}", parameterGatheringMessage.getActivateYn());
        logger.info("modifyDate                                   : {}", parameterGatheringMessage.getModifyDate());

        ChattingDayGatheringMessage resultGatheringMessage = new ChattingDayGatheringMessage();

        if(chattingDayGatheringMessageService.updateDeactivateAllGatheringMessage(parameterGatheringMessage)) {
            resultGatheringMessage.setResult("SUCCESS");
        } else {
            resultGatheringMessage.setResult("FAIL");
        }

        return resultGatheringMessage;
    }
}

